import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import Cookies from "js-cookie"

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/bind', '/register']

router.beforeEach((to, from, next) => {
  console.log("from.path:", from.path)
  console.log("to.path:", to.path)
  NProgress.start()
  if (getToken()) { // 拦截所有带token的请求
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/login') { // 带token跳转向/login时重定向跳到/
      next({ path: '/' })
      NProgress.done()
      // 客户端退出系统
    } else if ((from.path === '/client/home' && to.path === '/index') || (from.path === '/client/profile' && to.path === '/index') || (from.path === '/client/myborrow' && to.path === '/index') || (from.path === '/client/borcart' && to.path === '/index')) {  // 从/client/*跳转回/index时清空登录记录
      NProgress.done();
      store.dispatch('LogOut').then(() => {
        next({ path: '/' })
      })
      // 客户端放行
    } else if (to.path === '/client' || to.path === '/client/home' || to.path === '/client/profile' || to.path === '/client/myborrow' || to.path === '/client/borcart') {
      next() // 路由管道放行
    } else if (from.path === '/' && to.path === '/dev-api/*') { // 所有从/来，去/dev-api/*的路由，文件打印路径
      next() // 路由管道放行
    } else { // 带token的，除了上面几个路由的所有请求
      console.log("拦截/xxx")
      const loginType = Cookies.get("loginType");
      if (loginType === '2') { // 管理平台
        if (store.getters.roles.length === 0) {
          // 判断当前用户是否已拉取完user_info信息
          store.dispatch('GetInfo').then(() => {
            store.dispatch('GenerateRoutes').then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            })
          }).catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
              next({ path: '/' })
            })
          })
        } else {
          next()
        }
      } else if (loginType === '1') { // 利用平台
        next({ path: '/client' })
      } else {
        Message.error("loginType异常，请联系管理员")
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      console.log("无token跳转登录界面")
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
